<?php

class Post {
    // DB stuff
    private $conn;
    private $table;//表名

    // Constructor with DB
    public function __construct($db) {
        $this->conn = $db;
    }

    /**
     * 加密函数
     * @param $data :array
     */
    public function to_md5($data){
        //传入的是一个数组
        foreach ($data as $key=>$value){
            $value = md5($value);
        }
    }

    /**
     * Get Posts
     * @return array
     */
    public function read() {
        $query = 'SELECT * FROM `dt_users`';


        // Prepare statement
        $stmt = $this->conn->prepare($query);

        // Execute query
        $stmt->execute();

        return $stmt;
    }

    /**
     * dt_users插入信息，相当于注册
     * @param $Dealdatas :array
     * @return false|string
     */
    public function insert($Dealdatas)
    {
        # 传入一个二维数组
        $Dealdata= $Dealdatas['data'];
        //插叙插入之前的最大id值
        $res = $this->count_id("users");
        # 特判传入的值是否为空
        $not_empty = (!empty($Dealdata['username']) && !empty($Dealdata['password']) && !empty($Dealdata['nickname']) && !empty($Dealdata['email']) ) ;
        #进行加密
        $Dealdata['password'] = password_hash($Dealdata['password'],PASSWORD_DEFAULT);
        if ($res && $not_empty){
            //sql插入语句
            $sql = "insert into users(login,passwd,email,nickname)values('{$Dealdata['username']}','{$Dealdata['password']}','{$Dealdata['email']}','{$Dealdata['nickname']}')";
            //预处理sql语句
            $this->conn->prepare($sql)->execute();
        }


        //插入之后的最大id值
        $new_res = $this->count_id("users");
        if ($new_res == $res + 1 ) {
            $result = array(
                'status' => '200',
                'msg' => '注册成功'
            );
        }else {
            //如果没有插入成功，就返回 0
            $result = array(
                'status' => '201', #假设登陆失败，返回错误码是204（记于3.21），之后需要和xzw商量返回错误码
                'msg' => '注册失败'
            );
        }
        return  $result;
    }

    /**
     * 判断是否登陆成功
     * @param $getdata :array
     * @return bool
     */
    public function signin($getdata) {
        //var_dump($getdata);
        //$sql = "select user_pass from dt_users where user_login='{$getdata['username']}'";
        $sql = "select * from users where login='{$getdata['username']}' ";
        $result = $this->conn->query($sql)->fetch();
        //var_dump($result);
        //var_dump($res);
        return $result;
    }

    /**
     * 判断邮箱是否正确
     * @param $email :string
     * @return bool
     */
    public function ExistEmail($email) {
        $sql = "select count(email) from users where email='{$email}' ";
        $res = $this->conn->query($sql)->fetch();
        if ($res[0]>=1){
            //邮箱已经存在
            return true;
        }else{
            //邮箱不存在
            return false;
        }
    }

    /**
     * 修改用户密码
     * @param $email
     * @param $passwd
     * @return false|string
     */
    function UpdatePasswd($email,$passwd) {

        $sql = "update dt_users set user_pass='{$passwd}' where user_email='{$email}' ";
        $res1 = $this->conn->prepare($sql)->execute();
        $getsql = "select user_pass from dt_users where user_email='{$email}'";
        $res = $this->conn->prepare($getsql)->execute();

        if ($res == $passwd ) {
            return json_encode(
                array(
                    'status'=>200,
                    'msg'=>'修改密码成功',
                ),
                JSON_UNESCAPED_UNICODE
            );
        }
        else{
            return json_encode(
                array(
                    'status'=>201,
                    'msg'=>'修改密码失败，请稍后再试',
                ),
                JSON_UNESCAPED_UNICODE
            );
        }
    }

    /**
     * 邮箱或是密码登陆
     * @param $getdata :array
     * @return array
     */
    public function Emailin($getdata) {
        $sql = "select * from users where (email='{$getdata['username']}' and passwd='{$getdata['password']}')";
        $num = $this->conn->query($sql)->fetch();
        return $num;
    }

    /**
     * 验证用户名是否已经存在
     * @param $data-string
     * @return bool
     *
     */
    public function ExistUsername($data)
    {
        //传入一个字符串，判断是否已经注册为用户名
        $sql = "select count(login) from users where login='{$data}'";
        $res = $this->conn->query($sql)->fetch();
        if ($res[0]!=0){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 查询用户的激活码activation_key
     * @param $data :email
     * @return mixed :activation_key
     */
    public function Search_activation_key($data) {
        //传入：邮箱
        //返回：激活码activation_key
        $sql = "select user_activation_key from dt_users where user_email='{$data}'";
        $res = $this->conn->query($sql)->fetch();
        return $res[0];
    }

    /**
     * 插入用户UA数据
     * @param $data :array
     */
    public function insert_status($data) {
        //传入一个数组
        $sql = "select ID,user_email from dt_users where user_email='{$data['email']}' ";
        $res = $this->conn->query($sql)->fetch();
        var_dump($res);
        $sql = "insert into status_history(OS,ip,browser,status,user_id)values('{$data['OS']}','{$data['ip']}',
                '{$data['browser']}','3','{$res['ID']}')";

        $this->conn->prepare($sql)->execute();
    }

    /**
     * 查询用户的UA数据
     * @param $data :string
     * @return array
     */
    public function Search_UA($data) {
        $sql = "SELECT * from status_history where user_id='{$data}' ORDER BY id desc limit 1";
        $res = $this->conn->query($sql)->fetch();
        return $res;
    }

    /**
     * 查询dt_users返回单个查询条件的结果
     * @param $column
     * @param $data
     * @return array
     */
    public function Search_option($column,$data) {
        $sql = "select * from dt_users where $column='$data'";
        //拿到数据的返回结果---数组
        $res = $this->conn->query($sql)->fetch();
        return $res;

    }

    /**
     * 通过用户的id查询用户的最新的头像信息并返回一个数组
     * @param $data_id :int/string
     * @return array
     */
    public function Search_icon($data_id) {
        $sql = "select * from portrait_image where user_id='{$data_id}' ";
        $res = $this->conn->query($sql)->fetch();
        return $res;
    }

    /**
     * 向用户的dt_icons表中插入数据
     * @param $data :array
     * @return false|string
     */
    public function Insert_icon($data) {
        //{"attachment_id":"" , "path":"","ori_size":"","resize":""}
        $res = $this->count_id("portrait_image");
        $not_empty = !empty($data['user_id']) && !empty($data['path']);
        if ($not_empty) {
            $sql = "insert into portrait_image(user_id,url)
                values('{$data['user_id']}','{$data['path']}')";

            //执行sql语句
            $this->conn->prepare($sql)->execute();
            $new_res = $this->count_id("portrait_image");
            if ($res + 1 == $new_res) {
                //插入成功
                $result = json_encode(
                    array(
                        'status' => 200,
                        'msg' => '数据插入成功',
                    ),
                    JSON_UNESCAPED_UNICODE
                );
            } else {
                //插入不成功
                $result = json_encode(
                    array(
                        'status' => 200,
                        'msg' => '数据插入不成功',
                    ),
                    JSON_UNESCAPED_UNICODE
                );
            }
        }
        else{
                //必填项不为空
                $result = json_encode(
                    array(
                        'status' => 201,
                        'msg' => '必填项不能为空',
                    ),
                    JSON_UNESCAPED_UNICODE
                );
            }
            return $result;

    }

    public function Insert_icon_puls($user_id,$url){
        $sql = "insert into portrait_ image(user_id,url)
                values('{$user_id}','{$url}')";
        $this->conn->prepare($sql)->execute();
        return true;

    }

    /**
     * 创建用户的项目树
     * @param $data :array
     * @return false|string
     */
    public function Insert_tree($data) {
        $id = $this->max_id("dreamtree");
        //进行数据的插入
        $sql = "insert into dreamtree(name,Introduction,user_id)
            values('{$data['name']}','{$data['Introduction']}','{$data['user_id']}')";
        //执行sql语句
        $this->conn->prepare($sql)->execute();

        //获取插入后的最大id
        $new_id = $this->max_id("dreamtree");
        if($new_id == $id + 1) {
            $result = json_encode(
                array(
                    'status'=>200,
                    'msg'=>'项目创建成功',
                ),JSON_UNESCAPED_UNICODE
            );
        }else{
            $result = json_encode(
                array(
                    'status'=>201,
                    'msg'=>'项目创建失败,请稍后再试',
                ),JSON_UNESCAPED_UNICODE
            );
        }

        return $result;
    }

    /**
     * 查询table表最大的id
     * @param $table :string
     * @return number
     */
    public function max_id($table) {
        $sql = "select max(id) from $table";
        $res = $this->conn->query($sql)->fetch();
        return $res[0];
    }

    /**
     * 查询table表的id总数
     * @param $table
     * @return number
     */
    public function count_id($table) {
        $sql = "select count(id) from $table";
        $res = $this->conn->query($sql)->fetch();
        return $res[0];
    }

    /**
     * 在dt_tree里面查询用户创建的树
     * @param $user_id
     * @return array
     */
    public function Search_create_tree($user_id) {
        $sql = "select * from dt_tree where main_id = $user_id";
        $result = $this->conn->query($sql)->fetchALL();
        return $result;
    }

    /**
     * 在user_link_tree里面查询用户参与的项目树
     * @param $user_id
     * @return array
     */
    public function Search_join_tree($user_id) {
        $sql = "select * from user_link_tree where user_id = $user_id";
        $result = $this->conn->query($sql)->fetchALL();
        return $result;
    }

    /**
     * 在dt_tree中查询已经完成的项目树
     * @param $user_id
     * @return array
     */
    public function Search_completed_tree($user_id) {
        $sql = "select * from dt_tree where main_id = $user_id and status = 1";
        $result = $this->conn->query($sql)->fetchALL();
        return $result;
    }

    /**
     * 删除dt_tree里的某一行数据
     * @param $id
     * @return array
     */
    public function Delete_user_tree($id,$user_id) {
        $res = $this->count_id("dreamtree");
        $sql = "delete from dreamtree where id='{$id}' and user_id='{$user_id}'";
        $this->conn->prepare($sql)->execute();
        $new_res = $this->count_id("dreamtree");

        if ($res - 1 == $new_res) {
            $result = array(
                'status'=>200,
                'msg'=>'数据删除成功'
            );
            return $result;
        }else{
            $result = array(
                'status'=>201,
                'msg'=>'删除数据失败，请稍后再试'
            );
            return $result;
        }
    }

    /**
     * 通过用户名查询id
     * @param $name
     * @return mixed
     */
    public function Search_username_id($name){
        $sql = "select id from users where login='{$name}'";
        $res = $this->conn->query($sql)->fetch();
        return $res["id"];
    }

    /**
     * 通过邮箱查询id
     * @param $email
     * @return mixed
     */
    public function Search_emailto_id($email){
        $sql = "select id from users where email='{$email}'";
        $res = $this->conn->query($sql)->fetch();
        return $res["id"];
    }

    /**
     * 更新项目小卡片
     * @param $data
     * @return array
     */
    public function Update_tree($data){
        if(!empty($data)){
            if(array_key_exists('name',$data)){
                if(array_key_exists('Introduction',$data)){
                    $sql = "update dreamtree set name='{$data['name']}',Introduction='{$data['Introduction']}'
                        where id='{$data['id']}'";
                }else{
                    $sql = "update dreamtree set name='{$data['name']}' where id='{$data['id']}'";
                }
            }
            else{
                if(array_key_exists('Introduction',$data)){
                    $sql = "update dreamtree set Introduction='{$data['Introduction']}'
                        where id='{$data['id']}'";
                }else{
                    $result = array(
                        "status"=>201,
                        "msg"=>"修改的数据不能为空哦"
                    );
                    return $result;
                }
            }
        }
        else{
            $result = array(
                "status"=>201,
                "msg"=>"修改的数据不能为空哦"
            );
            return $result;
        }
        $this->conn->prepare($sql)->execute();
        $result = array(
            "status"=>200,
            "msg"=>"项目树更新成功"
        );
        return $result;
    }

    /**
     * 添加项目收藏
     * @param $data
     * @return bool
     */
    public function Insert_collection($data){
        try{
            $sql = "insert into collection(user_id,project_id)values ('{$data['user_id']}','{$data['project_id']}')";
            $this->conn->prepare($sql)->execute();
            return true;
        }catch (PDOException $e){
            //echo "Error:".$e;
            return false;
        }
    }

    /**
     * 查询当前项目是否收藏
     * @param $data
     * @return bool
     */
    public function Search_is_collection($data){
        $sql = "select user_id from collection where project_id='{$data['project_id']}'";
        $res = $this->conn->query($sql)->fetch();
        if ($res['user_id'] == $data['user_id']) {
            return true;
        }else{
            return false;
        }
    }

    /**
     * 取消收藏就是在表里面删除查询的哪一行
     * @param $data
     * @return bool
     */
    public function Delete_collection($data){
        try{
            $sql = "delete from collection 
        where user_id='{$data['user_id']}' and project_id='{$data['project_id']}'";
            $this->conn->prepare($sql)->execute();
            return true;
        }catch (PDOException $e){
            return false;
        }


    }

    /**
     * 创建收藏夹
     * @param $data
     * @return bool
     */
    public function Create_Favorites($data){
        try{
            $sql = "insert into t_collection_list(user_id,name,Introduction)
            values('{$data['user_id']}','{$data['name']}','{$data['Introduction']}')";
            $this->conn->prepare($sql)->execute();
            return true;
        }catch (PDOException $e){
            return false;
        }
    }

    /**
     * 更新收藏夹信息
     * @param $data
     * @return bool
     */
    public function Update_Favorites($data){
        try{
            if(!empty($data['name'])){
                if(!empty($data['Introduction'])){
                    $sql = "update t_collection_list set name='{$data['name']}',Introduction='{$data['Introduction']}'
                    where user_id='{$data['user_id']}' and id='{$data['Favorites_id']}'";
                }else{
                    $sql = "update t_collection_list set name='{$data['name']}'
                    where user_id='{$data['user_id']}' and id='{$data['Favorites_id']}'";
                }
            }else{
                if(!empty($data['Introduction'])){
                    $sql = "update t_collection_list set Introduction='{$data['Introduction']}'
                    where user_id='{$data['user_id']}' and id='{$data['Favorites_id']}'";
                }else{
                    return false;
                }
            }
            $this->conn->prepare($sql)->execute();
            return true;
        }catch (PDOException $e){
            return true;
        }
    }

    /**
     * 删除收藏夹
     * @param $data
     * @return bool
     */
    public function Delete_Favorites($data){
        try{
            $sql = "delete from t_collection_list where id='{$data['id']}' and user_id='{$data['user_id']}'";
            $this->conn->prepare($sql)->execute();
            return true;
        }catch (PDOException $e){
            return false;
        }
    }

    /**
     * 个人信息认证
     * @param $data
     * @param string $table
     * @return bool
     */
    public function Insert_Futhentication($data,$table=""){
        try{
            $sql = "insert into $table()values()";
            $this->conn->prepare($sql)->execute();
            return true;
        }catch (PDOException $e){
            return false;
        }
    }

    /**
     * 做测试专用函数
     * @param $data
     * @return bool
     */
    public function test_function($data){
        $flag=0;
        $res=null;
        $sql = "select id from t_collection_list where user_id='{$data['user_id']}'";
        $stmt = $this->conn->query($sql)->fetchALL();
        foreach ($stmt as $res){
            if($data['Favorites_id'] ==$res['id']){
                $flag=1;
                break;
            }
        }
        if($flag == 1){
            var_dump($res);
            return true;
        }else{
            return false;
        }
    }

    //阻止克隆对象
    private function __clone(){}

    //获取一条数据
    public function fetchOne($table, $where){
        $sql = "SELECT * FROM {$table} WHERE {$where}";
        $result = $this->pdo->query($sql)->fetch();
        return $result;
    }

    //获取全部数据
    public function fetchAll($table,$where = "2>1"){
        $sql = "SELECT * FROM {$table} WHERE {$where}";
        $result =  $this->pdo->query($sql)->fetchALL();
//        while($row = $result->fetch() ){
//            var_dump($row);
//        }
        //var_dump($result);
        return $result;
    }

    //获取数据条数
    public function rowCount($table,$where = "2>1"){
        $sql = "SELECT count(*) FROM {$table} WHERE {$where}";
        $result = $this->pdo->query($sql)->fetchall();
        //var_dump($result);
        //echo $result[0][0];
        return $result[0][0];
    }

    //插入数据
    public function insert_new($table,$data){
        try{
            $res = $this->rowCount($table);
            $keys = "";
            $values  = "";
            if($table=="user"){
                $data["pwd"]=md5($data["pwd"]);
                echo "pwd:".$data['pwd'];
            }
            foreach($data as $key=>$value){
                $keys .= "`{$key}`,";
                if($value == ""){
                    $values .= "null,";
                }else{
                    $values .= "'{$value}',";
                }
            }
            $keys = rtrim($keys,",");
            $values  = rtrim($values,",");
            $sql = "INSERT INTO {$table}({$keys}) VALUE({$values})";
            $this->pdo->prepare($sql)->execute();
            $new_res = $this->rowCount($table);
            if($new_res == $res + 1){
                return true;
            }
        }catch (PDOException $e){

            return false;
        }
    }

    //更新数据
    public function update($table,$data,$where){
        try{
            $update = "";
            foreach($data as $key => $value){
                $update .= "`{$key}`='{$value}',";
            }
            $update = rtrim($update,",");
            $sql = "UPDATE {$table} SET {$update} WHERE {$where}";
            return $this->pdo->prepare($sql)->execute();
        }catch (PDOException $e){
            //echo "Error:".$e->getMessage();
            return false;
        }

    }

    //删除数据
    public function delete($table,$where){
        try{
            $sql = "DELETE FROM {$table} WHERE {$where}";
            return $this->pdo->prepare($sql)->execute();
        }catch (PDOException $e){
            return false;
        }

    }

}


















